package com.tansuo365.test1.controller.kucunstuff;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tansuo365.test1.bean.kucunbean.DaohuoDetails;
import com.tansuo365.test1.bean.kucunbean.DaohuoZong;
import com.tansuo365.test1.service.kucunservice.DaohuoDetailsService;
import com.tansuo365.test1.service.kucunservice.DaohuoZongService;
import com.tansuo365.test1.service.otherservice.ShengouZhixingService;
import com.tansuo365.test1.service.kucunservice.WuliaoKucunRiZhiService;
import com.tansuo365.test1.service.kucunservice.WuliaoKucunSearService;
import com.tansuo365.test1.service.otherservice.ShengouZongService;
import com.tansuo365.test1.util.DateUtil;
import com.tansuo365.test1.util.StringUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@PropertySource(value = "classpath:danhao.properties")
@Api(value = "到货单相关控制层", tags = "", description = "")
@RestController
@RequestMapping("/admin/daohuodan")
public class DaohuoDanController {

    @Autowired
    private DaohuoZongService daohuoZongService;
    @Autowired
    private DaohuoDetailsService daohuoDetailsService;
    @Autowired
    private ShengouZhixingService shengouZhixingService;
    @Autowired
    private WuliaoKucunSearService wuliaoKucunSearService;
    @Autowired
    private WuliaoKucunRiZhiService wuliaoKucunRiZhiService;
    @Autowired
    private ShengouZongService shengouZongService;

    @Value("${danhao.daohuodan.prefix}")
    private String daohuodanPrefix;

    //到货单号生成

    /**
     * 获取申购单号 OK
     *
     * @param type
     * @return
     * @throws Exception
     */
    @Async
    @RequestMapping("/getDaohuoNumber")
    public ListenableFuture<String> genBillCode(String type) throws Exception {
        StringBuffer billCodeStr = new StringBuffer();
        billCodeStr.append(daohuodanPrefix);
        billCodeStr.append(DateUtil.getCurrentDateStr());
        String todayMaxShengouDanNumber = daohuoZongService.getTodayMaxDaohuoDanNumber();
        if (todayMaxShengouDanNumber != null) {
            billCodeStr.append(StringUtil.formatCode(todayMaxShengouDanNumber));
        } else {
            billCodeStr.append("0001");
        }
        return new AsyncResult<>(billCodeStr.toString());
    }

    @RequestMapping("/getSelective")
    public Map<String, Object> getDaohuoDan(DaohuoZong daohuoZong, @RequestParam(value = "page", required = true) Integer page, @RequestParam(value = "rows", required = true) Integer rows) {
        if (daohuoZong == null) {
            return null;
        }
        System.out.println("项目名称:" + daohuoZong.getXiangmumingcheng());
        Map<String, Object> resultMap = new HashMap<>();
        PageHelper.startPage(page, rows);
        List<DaohuoZong> daohuoZongsList = daohuoZongService.listDaohuoZong(daohuoZong);
        PageInfo<DaohuoZong> pageInfo = new PageInfo<DaohuoZong>(daohuoZongsList);
        resultMap.put("rows", pageInfo.getList());
        resultMap.put("total", pageInfo.getTotal());
        return resultMap;
    }

    //验收单绑定到货单 回填数据
    @RequestMapping("/bangdingDaohuo")
    public Map<String, Object> getDaohuodanById(DaohuoZong daohuoZong) {
        Map<String, Object> resultMap = new HashMap<>();
//        List<ShengouZong> shengouZong1 = shengouZongService.listShengouZong(shengouZong);
        List<DaohuoDetails> daohuoDetailsList = daohuoDetailsService.listDaohuoDetailsByZongId(daohuoZong.getId());
//        resultMap.put("shengouZong",shengouZong1.get(0));
        resultMap.put("daohuoDetailsList", daohuoDetailsList);
        resultMap.put("success", true);
        return resultMap;
    }

    /**
     * 根据zongzhang总表的id查询对应的子表数据 分页
     *
     * @param page
     * @param rows
     * @return 根据总表id遍历查询详细的物料集合
     */
    @RequestMapping("/listDetailsByZId")
    public Map<String, Object> listDetailsByZongId(DaohuoDetails daohuoDetails, @RequestParam(value = "page", required = true) Integer page, @RequestParam(value = "rows", required = true) Integer rows) {
        if (daohuoDetails == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        PageHelper.startPage(page, rows);
        List<DaohuoDetails> daohuoDetailsList = daohuoDetailsService.listDaohuoDetailsSelective(daohuoDetails);
        PageInfo<DaohuoDetails> pageInfo = new PageInfo<DaohuoDetails>(daohuoDetailsList);
        resultMap.put("rows", pageInfo.getList());
        resultMap.put("total", pageInfo.getTotal());
        return resultMap;
    }

    /**
     * 保存申购总表+子表数据 OK
     *
     * @return
     */
    //1.到货单保存后,同时写入申购数量,到货数量到申购执行汇总
    //2.到货单保存后,同时写入库存查询表,申购量/到货量,进行计算的(未到货量)
    @RequestMapping("/save")
    @Transactional
    public Map<String, Object> save(HttpSession session, DaohuoZong daohuoZong, @RequestParam("wuliaoDaohuoDetailsJson") String wuliaoDaohuoDetailsJson) {
        if (daohuoZong == null || wuliaoDaohuoDetailsJson == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        Gson gson = new Gson();
        List<DaohuoDetails> daohuoDetailsList = gson.fromJson(wuliaoDaohuoDetailsJson, new TypeToken<List<DaohuoDetails>>() {
        }.getType());
        daohuoZong.setFounder((String) session.getAttribute("truename"));
        //save时,先保存大表,大表返回id后再保存附表
        int insertCode = daohuoZongService.saveZongAndDetails(daohuoZong, daohuoDetailsList);
        //save时,保存到货单数据到申购执行,选择其中daohuoDetailsList中shengoudanhao不为空的进行保存转换
        int zhixingSaveCode = shengouZhixingService.saveDaohuoBindShengou(daohuoDetailsList, daohuoZong);
        if (insertCode > 0 && zhixingSaveCode > 0) {
            resultMap.put("success", true);
            resultMap.put("msg", "保存成功.");
//            wuliaoKucunSearService.
            return resultMap;
        } else {
            resultMap.put("success", false);
            resultMap.put("errorInfo", "保存失败");
            return resultMap;
        }
    }

    /**
     * 更新到货总表
     *
     * @return
     */
    @RequestMapping("/update")
    public Map<String, Object> update(DaohuoZong daohuoZong) {
        if (daohuoZong == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        int updateCode = daohuoZongService.updateByPrimaryKeySelective(daohuoZong);
        if (updateCode > 0) {
            resultMap.put("success", true);
            return resultMap;
        } else {
            resultMap.put("success", false);
            return resultMap;
        }
    }

    /**
     * 删除  这里的删除同样删除了子表数据
     *
     * @param ids
     * @return
     */
    @RequestMapping("/delete")
    @Transactional
    public Map<String, Object> deleteBatch(@RequestParam("ids[]") Integer[] ids) throws Exception{
        Map<String, Object> resultMap = new HashMap<>();
        if (ids == null || ids.length == 0) {
            resultMap.put("success", false);
            resultMap.put("errorInfo", "请选中条目进行删除");
            return resultMap;
        }
        int ziDelCode = 0;
        int delBindCode = shengouZhixingService.deleteDaohuoBindShengou(ids);//删除申购执行中到货数据的数值(update-少)
        int delToKC = wuliaoKucunRiZhiService.insertButDeleteDaohuoShu(ids);
        int code = daohuoZongService.deleteBatchByPKArr(ids);  //批量删除到货主表
        List<String> shengoudans = null;
        if (code > 0) {
            //删除前先获取他们的对应申购单s
            shengoudans = daohuoDetailsService.listDuiyingShengouDan(ids);
            //再删除
            ziDelCode = daohuoDetailsService.deleteByZongIdArr(ids); //批量删除到货详细根据ids条目
        }
        if(ziDelCode>0){
//            再判定是否还有这些对应申购单
            List<DaohuoDetails> daohuoDetails = daohuoDetailsService.listByDuiyingShengoudans(shengoudans);
            if(CollectionUtils.isEmpty(daohuoDetails)){
                for(String shengoudan:shengoudans){
                    int i = shengouZongService.updateCanDeleteToCan(shengoudan);
                }
            }
        }
        if (code > 0 && ziDelCode > 0 && delBindCode>0 && delToKC > 0) {
            resultMap.put("success", true);
            return resultMap;
        } else {
            resultMap.put("success", false);
            return resultMap;
        }
    }

}
